class Zerocms::UniqValidator < ActiveModel::Validator
	def validate(record)
		unless record.skip_slug_validation?
			record.errors[:base] << "#{I18n.t('zerocms.admin.post.message.requires_different_slug')}" if Zerocms::TermTaxonomy.where(slug: record.slug).where.not(id: record.id).where("#{Zerocms::TermTaxonomy.table_name}.taxonomy" => record.taxonomy).where("#{Zerocms::TermTaxonomy.table_name}.parent_id" => record.parent_id).size > 0
		end
	end
end

class Zerocms::TermTaxonomy < ActiveRecord::Base
  include Zerocms::Metas
  include Zerocms::CustomFieldsRead
	self.table_name = "#{PluginRoutes.static_system_info["db_prefix"]}term_taxonomy"

	before_validation :before_validating
  before_destroy :destroy_dependencies

	# validates
  validates :name, :taxonomy, presence: true
  validates_with Zerocms::UniqValidator

  # relations
  has_many :term_relationships, :class_name => "Zerocms::TermRelationship", :foreign_key => :term_taxonomy_id, dependent: :destroy
  belongs_to :parent, class_name: "Zerocms::TermTaxonomy", foreign_key: :parent_id
  belongs_to :owner, class_name: PluginRoutes.static_system_info['user_model'].presence || 'Zerocms::User', foreign_key: :user_id

	# all children taxonomy
	# sample: sub categories of a category
	def children
		logger.debug 'get children of TermTaxonomy'
		Zerocms::TermTaxonomy.where("#{Zerocms::TermTaxonomy.table_name}.parent_id = ?", self.id)
	end

  # return all menu items in which this taxonomy was assigned
  def in_nav_menu_items
    Zerocms::NavMenuItem.where(url: self.id, kind: self.taxonomy)
  end

	# permit to skip slug validations for children models, like menu items
  def skip_slug_validation?
    false
  end

	private
  # callback before validating
  def before_validating
  	logger.debug 'TermTaxonomy before_validating'
    slug = self.slug
    slug = self.name if slug.blank?
    self.name = slug unless self.name.present?
    self.slug = slug.to_s.parameterize.try(:downcase)
    logger.debug "#{self.to_s}"
  end

  # destroy all dependencies
  # unassign all items from menus
  def destroy_dependencies
  	logger.debug 'TermTaxonomy destroy_dependencies'
    # in_nav_menu_items.destroy_all
  end
end